<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<header>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0"/>
    <meta name="theme-color" content="#000000"/>
</header>
<button type="button" onclick="callArkTS()">Click Me!</button>
<button type="button" onclick="openPage01()">Open Inner Page01!</button>
<button type="button" onclick="getArray()">getArray</button>
<button type="button" onclick="getObject()">getObject</button>
<h5 id="text">
    这是一个测试信息，默认字体为黑色，调用runJavaScript方法后字体为绿色，调用runJavaScriptCodePassed方法后字体为红色</h5>
<h5 id="input">展示获取原生数据</h5>

<div>
    <input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/>
    <input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/>
</div>
<p id="output">display received message send from ets</p>

<script>
    // 调用有参函数时实现。
    var param = "param: JavaScript Hello World!";
    function htmlTest(param) {
        document.getElementById('text').style.color = 'green';
        console.log(param);
    }
    // 调用无参函数时实现。
    function htmlTest() {
        document.getElementById('text').style.color = 'green';
    }
    // Click Me！触发前端页面callArkTS()函数执行JavaScript传递的代码。
    function callArkTS() {
        // changeColor();
        document.getElementById('input').innerHTML = JSON.stringify({name:'aaa', age:20});
    }
    // 调用ArkTs
    function openPage01() {
         openPage.openPage01();
    }

    function getArray(){
        var getArray = openPage.getArray();
        document.getElementById('input').innerHTML = JSON.stringify(getArray);
        console.log('zhu', getArray);
    }

    function getObject(){
        var getObject = openPage.getObject();
        document.getElementById('input').innerHTML = getObject['name'];
        console.log('zhu', getObject);
    }


    var h5Port;
    var output = document.getElementById('output');
    window.addEventListener('message', function(event){
        if(event.data === '__init_port__'){
            if(event.ports[0]!==null){
                //保存从应用测发送过来的端口
                h5Port = event.ports[0];
                h5Port.onmessage = function(event){
                    var result = `from ets:${JSON.stringify(event.data)}`;
                    output.innerHTML = result;
                }
            }
        }
    });

    function PostMsgToEts(data){
        if(h5Port){
            h5Port.postMessage(data);
        }else {
            console.error('h5Port is null, Please initialize first');
        }
    }

</script>
</body>
</html>